import styles from './index.less';
import { memo, PureComponent } from 'react';
import { CompnentEnums } from '@/Enums';
import { getEvents } from '@/utils';
import getProps from '@/utils/getProps';
const singleTags = ['br', 'hr', 'Img', 'Input', 'param', 'meta', 'Link']
/**
 * 节点数据发生变化
 */
let onChangeData: (data: API.Node) => void;
class Node extends PureComponent <API.Node>{

  constructor(props: API.Node) {
    super(props);
  }

  render() {
    const { tree, scope } = this.props;
    const type = Object.prototype.toString.call(tree);
  
    if (!tree) return <></>;

    if (type === '[object Array]') {
      return (
        <>
          {tree.map((node: API.Node) => {
            const Comp = CompnentEnums[node.tag!];
     
            if (singleTags.includes(node.tag!)) {
              return (
                <Comp key={node.id} style={node.style} className={styles.node} {...getProps(scope, node.props)} {...getEvents(scope, node.events)} />
              )
            }
            return (
              <Comp key={node.id} style={node.style} className={styles.node} {...getProps(scope, node.props)} {...getEvents(scope, node.events)}>
                <Node id={node.id} tree={node.children} scope={scope} />
              </Comp>
            );
          })}
        </>
      );
    } else if (type === '[object String]') {
      return tree
    } else if (type === '[object Object]') {
      const Comp = CompnentEnums[tree.tag];
      if (singleTags.includes(tree.tag)) return (
        <Comp className={styles.node} key={tree.id} style={tree.style} {...tree.props} {...getEvents(scope, tree.events)}/>
      )
      return (
        <Comp className={styles.node} key={tree.id} style={tree.style} {...tree.props}>
          <Node tree={tree.children} key={tree.id} id={tree.id} scope={scope} {...getEvents(scope, tree.events)}/>
        </Comp>
      );
    }
  }
}
function TreeComponent(props: API.ITreeComponentProps) {

  return (<>{
    props.tree.map((node) => <Node tree={node} key={node.id} id={node.id} scope={props.scope}/>)
  }</>)
}

export default memo(TreeComponent);